open Common
open Printf
open ExtLib

type t = { path: string }

module type PROJECT =
sig
	type t
	val version : t -> int
	val description : t -> string
	val name : t -> string
	val open_store : t -> MoviesDal.movies_dal
	val close_store : t -> unit
end

let dir_exists path =
	try
		let exists = Sys.is_directory path in
			if not exists then
				failwith "There is a not directory on specified path";
			true
	with
		| Sys_error(_) ->
				false

let file_exists path =
	try
		let exists = not (Sys.is_directory path) in
			if not exists then
				failwith "There is a not file on specified path";
			true
	with
		| Sys_error(_) ->
				false

module Project = struct
	type t = { name : string; path : string}
			
	let path p =
		p.path

	let embeded_files_path p =
		Filename.concat p.path "files"

	let store_path p =
		Filename.concat p.path "store.db"

	let name p =
		p.name
			
	let open_store p =
		new MoviesDal.movies_dal (store_path p)

	let close_store p =
		()

	let create path name =
		let newPrj = {path = path; name = name} in
		if not (dir_exists (embeded_files_path newPrj)) then
			Unix.mkdir (embeded_files_path newPrj) 0o700;
		newPrj |> open_store |> close_store;
		newPrj

	let version p =
		0
			
	let description p =
		""
end

let prj_path root name = Filename.concat root.path name
	
let open_projects path =
	if not(dir_exists path) then (
		Unix.mkdir path 0o700;
	);
	{ path = path }
	
let create prjs name =
	let newProjectPath = prj_path prjs name in
		if not (dir_exists newProjectPath) then (
			Unix.mkdir newProjectPath 0o700;
			Project.create newProjectPath name
		) else
			failwith "Another project with this name already created"
	
		
let load prjs name =
	let projectPath = prj_path prjs name in
		if dir_exists projectPath then
			Project.create projectPath name
		else
			failwith "There is no such project"
		
let remove prjs prj =
	true
		
let exists prjs name =
	dir_exists (prj_path prjs name)

let enum_projects_names root =
	 
	 Array.fold_right
		 (fun name l ->
				if Sys.is_directory (Filename.concat root name) then
					name :: l
				else
					l
		 )
		 (Sys.readdir root)
		 []


let enum_projets_names prjs =
	let prjsPath = prjs.path in
	assert( (dir_exists prjsPath) == true );
	Array.fold_right
		(fun name l ->
			 if Sys.is_directory (Filename.concat prjsPath name) then
				 name :: l
			 else
				 l
		)
		(Sys.readdir prjsPath)
		[]
